package com.kdd.campus.sh.controller;

import com.kdd.campus.common.entity.CommonResult;
import com.kdd.campus.common.entity.FastDFSFile;
import com.kdd.campus.common.util.FastDFSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Auther: fcp
 * @Date: 2020/3/23 10:47
 * @Description:
 */
@Api(value = "FileController" , tags = "FileController")
@RestController
@RequestMapping("file")
public class FileController {

    @PostMapping("upload")
    @ApiOperation(value = "上传文件",httpMethod = "POST")
    @ApiImplicitParam(paramType = "form", name = "multipartFile", value = "上传的文件", dataType = "file")
    public CommonResult upload(MultipartFile multipartFile) {
        try {
            if (multipartFile == null) {
                throw new RuntimeException("文件不存在");
            }
            // 获取文件完整名称
            String originalFilename = multipartFile.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                throw new RuntimeException("文件名不存在");
            }
            // 获取文件的后缀名
            String ext = originalFilename.substring(originalFilename.indexOf(".") + 1);

            // 获取文件的内容
            byte[] content = multipartFile.getBytes();
            // 封装上传文件对象
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, content, ext);
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);

            //封装返回结果
            String url = null;
            url = FastDFSClient.getTrackerUrl() + uploadResult[0] + "/" + uploadResult[1];
            return CommonResult.success(url);
        } catch (IOException e) {
            return CommonResult.failed(e.getMessage());
        }
    }

}
